<?php

namespace app\common\model\xilumarket;

use app\common\library\Auth;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\Hook;
use think\Log;
use think\Model;
use function fast\array_get;


class UserFocus extends Model
{

    // 表名
    protected $name = 'xilumarket_user_focus';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    public function focusUser(){
        return $this->belongsTo(User::class,'focus_user_id','id',[],'inner')->setEagerlyType(0);
    }

    /**
     * 关注用户
     */
    public static function getFocusUser($params,$user_id){
        $pagesize = array_get($params,'pagesize',10);
        return static::with(['focusUser'=>function($query){
            $query->withField(['id','nickname','avatar']);
        }])
            ->where('user_id',$user_id)
            ->paginate($pagesize);
    }

    /**
     * @param int $userId
     * @param int $recordId
     * @return bool|string true是已收藏状态, false是未收藏状态
     */
    public static function toggleFocus($userId, $recordId) {
        try {
            Db::startTrans();
            $model = static::where('user_id', $userId)
                ->where('focus_user_id', $recordId)
                ->find();
            if ($model) {
                $model->delete();
                $result = false;
            } else {
                $model = new UserFocus([
                    'user_id' => $userId,
                    'focus_user_id' => $recordId
                ]);
                if ($model->save() === false) {
                    Db::rollback();
                    throw new Exception($model->getError());
                }
                $result = true;
                Hook::listen("xilumarket_focus_message",$model);
            }
            Db::commit();
            return $result;
        }catch (\Exception $e) {
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            Db::rollback();
            return false;
        }
    }

    /**
     * 我的关注
     */
    public static function focusLists($params,$user_id){
        $pagesize = array_get($params,'pagesize',10);

        return User::alias("user")
            ->join("xilumarket_user_focus user_focus",'user_focus.focus_user_id=user.id')
            ->order("user_focus.id",'desc')
            ->field(['user.id','user_focus.user_id','user.nickname','user.avatar','user_focus.createtime'])
            ->where('user_focus.user_id',$user_id)
            ->paginate($pagesize)
            ->each(function ($row) use($user_id){
                $row->fans_count  = static::getFocusCount($row->id);
            });
    }

    /**
     * 我的粉丝
     */
    public static function fansLists($params,$user_id){
        $pagesize = array_get($params,'pagesize',10);

        return User::alias("user")
            ->join("xilumarket_user_focus user_focus",'user_focus.user_id=user.id')
            ->order("user_focus.id",'desc')
            ->field(['user.id','user_focus.user_id','user.nickname','user.avatar','user_focus.createtime'])
            ->where('user_focus.focus_user_id',$user_id)
            ->paginate($pagesize)
            ->each(function ($row) use($user_id){
                $row->fans_count  = static::getFocusCount($row->id);
                $row->is_focus_count = UserFocus::where('user_id',$user_id)->where('focus_user_id',$row->user_id)->count()?1:0;
            });
    }


    /**
     * 用户是否已关注
     * @param $userId
     * @param $recordId
     * @return bool
     */
    public static function isFocus($userId, $recordId) {
        if(!$userId || !$recordId)
            return false;
        return static::where('user_id',$userId)
                //->where('collection_type',$type)
                ->where('focus_user_id',$recordId)->count() > 0;
    }

    /**
     * 我关注的人数
     * @param $user
     * @return int|string
     * @throws \think\Exception
     */
    public static function getCount($user){
        return self::where('user_id',$user->id)->count('*');
    }

    //粉丝数
    public static function getFocusCount($user_id){
        return self::where('focus_user_id',$user_id)->count(1);
    }
}
